<!-- 审核详情弹窗 -->
<template>
  <a-modal :maskClosable="false" :destroyOnClose="true" :title="titleMap[type]" centered :width="800" v-model="visible">
    <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-model-item label="会员名称" class="_mb-5">
        <span>{{ form.proposer }}</span>
      </a-form-model-item>
      <a-form-model-item label="当前职务" class="_mb-5">
        <span>{{ form.levelName }}</span>
      </a-form-model-item>
      <template v-if="type === 'renewSet' || type === 'awaitPayDetail'">
        <a-form-model-item label="加入时间" class="_mb-5">
          <span>{{ form.joinTime }}</span>
        </a-form-model-item>
        <a-form-model-item label="到期时间" class="_mb-5">
          <div class="disFlxAC">
            <span class="_pr-10">{{ form.nowMemberEndTime }}</span>
            <DictTag :options="Dict.getLocal('paymentStatusDict')" :value="form.nowPaymentStatus" />
          </div>
        </a-form-model-item>
      </template>
      <a-form-model-item v-if="type !== 'renewSet' && type !== 'awaitPayDetail'" label="申请职务" class="_mb-5">
        <span>{{ form.levelName }}</span>
      </a-form-model-item>
      <a-form-model-item
        :label="type === 'renewSet' || type === 'awaitPayDetail' ? '续期职务' : '实际职务'"
        prop="levelId"
        :class="{ '_mb-5': disabled }"
      >
        <span v-if="disabled">{{ form.nowLevelName || form.levelName }}</span>
        <a-select v-else v-model="form.levelId" @select="val => handleLevelSelect(val)">
          <a-select-option v-for="item in levelList" :value="item.id" :key="item.id">{{ item.name }}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="缴费标准" class="_mb-5">
        <span>{{ form.membershipFees || 0 }}元/{{ form.allottedTime }}月</span>
      </a-form-model-item>
      <a-form-model-item
        :label="type === 'awaitPayDetail' ? '待缴金额（￥）' : '应缴金额（￥）'"
        prop="payMoney"
        :class="{ '_mb-5': disabled }"
      >
        <span v-if="disabled">{{ form.payMoney }}</span>
        <a-input-number v-else v-model="form.payMoney" :min="0" :max="1000000" style="width: 200px" />
        <span class="_ml-5">元</span>
      </a-form-model-item>

      <template v-if="type === 'awaitPayDetail'">
        <a-form-model-item label="缴费函" class="_mb-5">
          <span class="colorZS cup" @click="handleExport">查看缴费函</span>
        </a-form-model-item>
        <a-form-model-item label="本期缴费至" class="_mb-5">
          <span>{{ form.endTime }}</span>
        </a-form-model-item>
      </template>
      <template v-else>
        <a-form-model-item v-if="!disabled" label="会员续期" :class="{ '_mb-5': disabled }">
          <a-radio-group v-model="renewalType" @change="handleRenewalTypeChange">
            <a-radio :value="1">自定义到期时间</a-radio>
            <a-radio :value="2">固定周期续费</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="开始时间" prop="startTime" :class="{ '_mb-5': disabled }">
          <span v-if="disabled">{{ form.startTime }}</span>
          <a-date-picker v-else v-model="form.startTime" valueFormat="YYYY-MM-DD" @change="handleStartTimeChange" />
        </a-form-model-item>
        <a-form-model-item v-if="renewalType === 2" label="续费周期" prop="cycle" :class="{ '_mb-5': disabled }">
          <a-input-group compact class="width-20">
            <a-input-number
              v-model="form.cycle"
              style="width: 125px"
              id="inputNumber"
              :min="1"
              @change="handleCycleChange"
            />
            <a-select v-model="form.months" style="width: 58px" @change="handleMonthsChange">
              <a-select-option :value="12"> 年 </a-select-option>
              <a-select-option :value="1"> 月 </a-select-option>
            </a-select>
          </a-input-group>
          <a class="colorZS _ml-20">下次续期时间为：{{ form.endTime }}</a>
        </a-form-model-item>
        <a-form-model-item v-else label="到期时间" prop="endTime" :class="{ '_mb-5': disabled }">
          <span v-if="disabled">{{ form.endTime }}</span>
          <a-date-picker
            v-else
            v-model="form.endTime"
            valueFormat="YYYY-MM-DD"
            :showToday="false"
            :disabled-date="disabledDate"
            @change="handleEndTimeChange"
          />
          <a class="colorZS _ml-20">下次续期时间为：{{ form.endTime }}</a>
        </a-form-model-item>
      </template>

      <a-form-model-item
        v-if="type === 'memberSet' || type === 'renewSet'"
        label="缴费设置"
        prop="state"
        :class="{ '_mb-5': disabled }"
      >
        <a-radio-group v-model="form.state" :disabled="disabled || form.membershipFees === 0">
          <a-radio :value="0">设为待缴费</a-radio>
          <a-radio :value="1">设为已缴费</a-radio>
        </a-radio-group>
      </a-form-model-item>

      <a-form-model-item
        v-if="form.state === 1 || infoData.state === 1 || (type === 'payApproval' && form.paymentVoucher)"
        label="缴费信息"
        :class="{ '_mb-5': disabled }"
      >
        <UploadImg v-model="form.paymentVoucher" :disabled="disabled" />
      </a-form-model-item>
      <a-form-model-item v-if="infoData.updateTime" label="上次提交时间" class="_mb-5">
        <a>{{ infoData.updateTime }}</a>
      </a-form-model-item>

      <template v-if="type === 'memberSet'">
        <div class="title">其他设置</div>

        <a-form-model-item label="负责人、企业对外展示" :class="{ '_mb-5': disabled }">
          <a-switch v-model="form.memberOtherSettingsDto.show" default-checked :disabled="disabled" />
        </a-form-model-item>
        <a-form-model-item label="服务专员" :class="{ '_mb-5': disabled }">
          <a-select
            v-model="form.memberOtherSettingsDto.currentService"
            :disabled="disabled"
            placeholder="请选择"
            allowClear
          >
            <a-select-option v-for="item in attacheList" :value="item.id" :key="item.id">{{
              item.userName
            }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="标签分组" :class="{ '_mb-5': disabled }">
          <a-select v-model="form.memberOtherSettingsDto.groupIdList" mode="multiple" :disabled="disabled">
            <a-select-option v-for="item in groupingList" :value="item.id" :key="item.id">{{
              item.name
            }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="备注" :class="{ '_mb-5': disabled }">
          <a-textarea
            v-model="form.memberOtherSettingsDto.remarks"
            :disabled="disabled"
            placeholder="请输入备注信息，仅对管理员可见"
            :rows="4"
          />
        </a-form-model-item>
      </template>
    </a-form-model>

    <template slot="footer">
      <template v-if="type === 'memberSet' || type === 'renewSet'">
        <a-button v-if="!disabled" type="primary" @click="handleShowModal">确认提交</a-button>
        <a-button v-else type="primary" @click="visible = false">确 认</a-button>
      </template>
      <template v-else-if="type === 'awaitPayDetail'">
        <a-button type="primary" @click="type = 'renewSet'">修改续费</a-button>
      </template>
      <template v-else-if="type === 'payApproval'">
        <a-button @click="handleShowApprovalModal(2, '缴费驳回', '非必填，请输入驳回原因，指引会员重新提交')"
          >驳回</a-button
        >
        <a-button
          style="margin-left: 10px"
          type="primary"
          @click="
            handleShowApprovalModal(
              1,
              '缴费通过',
              '非必填，请输入指引会员下一步操作的提示语，例如加管理员微信，加会员群，完善名片等。'
            )
          "
          >缴费通过</a-button
        >
      </template>
      <template v-else>
        <a-button type="primary" @click="visible = false">确定</a-button>
      </template>
    </template>
    <PayModal ref="payModal" @success="settingSuccess" />
    <ApprovalModal ref="approvalModal" :type="2" @success="settingSuccess" />
  </a-modal>
</template>

<script>
import Form from '@/components/Form'
import PayModal from './payModal.vue'
import ApprovalModal from './approvalModal.vue'
import { MemberApplyById, MemberByIdMemberPaymenrecord, MemberSettingInfo, PaymentExport } from '@/api/member/member'
import { memberLevel, memberPostList } from '@/api/member/memberType'
import { attacheList } from '@/api/system/system'
import { getTagUserList } from '@/api/member/grouping'
import moment from 'moment'
import { reviewStatusEnum } from '@/enums/member'
import UploadImg from '@/components/UpFile/uploadImg'
import DictTag from '@/components/DictTag'

const defaultForm = {
  id: undefined,
  applyId: undefined,
  applyType: undefined,
  proposer: undefined,
  joinTime: undefined,
  nowMemberEndTime: undefined,
  nowPaymentStatus: undefined,
  levelName: undefined,
  paymentStatus: undefined,
  levelId: undefined,
  payMoney: undefined,
  startTime: moment(),
  endTime: undefined,
  cycle: 1,
  months: 12,
  state: 0,
  paymentVoucher: undefined,
  membershipFees: undefined,
  allottedTime: undefined,
  memberOtherSettingsDto: {
    memberPostId: undefined,
    groupIdList: [],
    currentService: undefined,
    remarks: undefined,
    show: true
  }
}

export default {
  components: {
    Form,
    PayModal,
    ApprovalModal,
    UploadImg,
    DictTag
  },
  data() {
    return {
      visible: false,
      labelCol: { span: 5 },
      wrapperCol: { span: 14 },
      form: defaultForm,
      nowLevelName: undefined,
      rules: {
        state: [{ required: true, message: '请选择缴费状态', trigger: 'change' }],
        levelId: [{ required: true, message: '请选择缴费职务', trigger: 'change' }],
        payMoney: [{ required: true, message: '请填写实缴金额', trigger: 'change' }],
        startTime: [{ required: true, message: '请选择本期缴费开始时间', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择本期缴费结束时间', trigger: 'change' }],
        cycle: [{ required: true, message: '请输入续费周期', trigger: 'change' }]
      },
      row: {},
      id: undefined,
      type: 'memberSet',
      stageList: [],
      // tabList: [],
      titleKey: 'mySite',
      currentApproval: 0,
      levelList: [],
      postList: [],
      attacheList: [],
      groupingList: [],
      isPayment: false,
      infoData: {},
      isChangeEndTime: false,
      renewalType: 1,
      titleMap: {
        renewSet: '会员续费设置',
        memberSet: '会员会费设置',
        payApproval: '缴费凭证审核',
        payApprovalDetail: '缴费凭证详情',
        awaitPayDetail: '待缴费详情'
      }
    }
  },
  computed: {
    disabled() {
      return (
        this.type === 'payApproval' ||
        this.type === 'payApprovalDetail' ||
        this.type === 'awaitPayDetail' ||
        this.isPayment
      )
    }
  },
  filters: {
    filterAllottedTime(val) {
      return (val && val / 12) || '--'
    }
  },
  watch: {},
  methods: {
    async show(data) {
      let { id, type, row } = data
      this.id = id
      this.type = type
      this.row = row && JSON.parse(row)
      this.renewalType = 1

      this.form = { ...defaultForm }

      this.isChangeEndTime = false
      this.visible = true

      await this.getLevelList()
      if (this.type === 'renewSet' || this.type === 'awaitPayDetail') {
        await this.getMemberSettingInfo()
        this.getMemberByIdMemberPaymenrecord()
      } else {
        this.getMemberApplyById()
      }

      if (this.type !== 'renewSet' && this.type !== 'awaitPayDetail') {
        this.getMemberPostList()
        this.getPageAttacheList()
        this.getGroupingList()
      }
    },
    handleShowModal() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (this.form.state === 0 && this.form.payMoney === 0)
            return this.$message.error('金额为0无需支付，请设为已缴费')
          // if (this.renewalType === 2) {
          //   this.form.endTime = moment(this.form.startTime).add(this.form.cycle * this.form.months, 'months').format('YYYY-MM-DD')
          // }
          console.log(this.form)
          this.$refs.payModal.show({ ...this.form, nowLevelName: this.nowLevelName }, this.type, this.form.state === 1)
        }
      })
    },
    handleShowApprovalModal(status, title, placeholder) {
      this.$refs.approvalModal.show({
        id: this.id,
        status,
        title,
        placeholder
      })
    },
    async getMemberApplyById() {
      let res = await MemberApplyById(this.id)
      this.setFields(res)
    },
    async getMemberByIdMemberPaymenrecord() {
      let res = await MemberByIdMemberPaymenrecord(this.id)
      this.setFields(res)
    },
    setFields(res) {
      let data = res.data || {}
      this.infoData = data
      console.log('this.infoData--->', this.infoData)
      Object.keys(this.form).forEach(k => {
        if (data[k]) this.form[k] = data[k]
      })
      this.form.proposer = data.memberName
      this.form.applyId = this.id
      this.form.id = data.id
      this.form.levelId = data.nowLevelId || data.levelId
      this.form.memberOtherSettingsDto.currentService =
        data.memberOtherSettingsDto &&
        data.memberOtherSettingsDto.currentService &&
        Number(data.memberOtherSettingsDto.currentService)
      this.form.memberOtherSettingsDto.show = data.memberOtherSettingsDto
        ? data.memberOtherSettingsDto.show === 1
        : true
      this.form.memberOtherSettingsDto.groupIdList =
        (data.memberOtherSettingsDto && data.memberOtherSettingsDto.groupIdList) || []
      this.isPayment = data.state === 1 && data.auditStatus != reviewStatusEnum.REJECT
      this.$set(this.form, 'nowLevelName', data.nowLevelName)
      if (!res.data) {
        let { applyType, memberName, levelId, levelName } = this.row
        // this.form.applyId = id
        this.form.applyType = applyType
        this.form.proposer = memberName
        this.form.levelName = levelName
        this.form.levelId = levelId
      }
      if (this.type === 'renewSet' || this.type === 'awaitPayDetail') {
        this.form.startTime = this.row.memberEndTime
        this.form.joinTime = this.row.joinTime
        this.form.nowMemberEndTime = this.row.memberEndTime
        this.form.nowPaymentStatus = this.row.paymentStatus
      }
      this.handleLevelSelect(this.form.levelId, true)
    },
    async getLevelList() {
      let res = await memberLevel()
      this.levelList = res.data || []
    },
    async getMemberPostList() {
      let res = await memberPostList()
      this.postList = res.rows || []
    },
    async getPageAttacheList() {
      let res = await attacheList({ attacheType: 'hyzy' })
      this.attacheList = res.data || []
    },
    async getGroupingList() {
      let res = await getTagUserList({ type: 0 })
      this.groupingList = res.data || []
    },
    onTabChange(key) {
      this.titleKey = key
    },
    handleLevelSelect(val, isDefault) {
      let item = this.levelList.find(f => f.id === val) || {}
      this.form.membershipFees = item.membershipFees || 0
      this.form.payMoney = isDefault ? this.infoData.payMoney || item.membershipFees : item.membershipFees || 0
      this.form.allottedTime = item.allottedTime || 12
      this.form.state = item.membershipFees === 0 ? 1 : 0
      //1、历史数据为待缴费，且不是默认加载时，可设置截止时间
      //2、默认加载，且截止时间为空时，可设置截止时间
      if (((this.form.state !== 1 && !isDefault) || (isDefault && !this.form.endTime)) && !this.isChangeEndTime) {
        this.form.endTime = moment(this.form.startTime)
          .add('month', this.form.allottedTime)
          .format('YYYY-MM-DD')
      }
      this.nowLevelName = item.name
    },
    disabledDate(current) {
      // Can not select days before today and today
      return current && current < moment().endOf('day')
    },
    handleStartTimeChange(val) {
      if (this.renewalType === 1) {
        this.form.endTime = moment(val)
          .add('month', this.form.allottedTime)
          .format('YYYY-MM-DD')
      } else {
        this.getEndTime()
      }
    },
    handleEndTimeChange(e) {
      this.isChangeEndTime = true
    },
    async getMemberSettingInfo() {
      let res = await MemberSettingInfo(this.id)
      this.row = res.data || {}
    },

    // 续费周期类型变更
    handleRenewalTypeChange(e) {
      if (e.target.value === 2) this.getEndTime()
    },

    // 续费周期变更事件
    handleCycleChange() {
      this.getEndTime()
      this.$refs.ruleForm.validateField('cycle')
    },
    // 续费周期单位变更事件
    handleMonthsChange() {
      this.getEndTime()
    },
    getEndTime() {
      this.form.endTime = moment(this.form.startTime)
        .add(this.form.cycle * this.form.months, 'months')
        .format('YYYY-MM-DD')
    },
    settingSuccess() {
      this.$emit('refresh')
      this.visible = false
    },
    async handleExport() {
      console.log('this.form--->', this.form)
      let {
        proposer,
        levelName,
        nowLevelName,
        membershipFees,
        payMoney,
        applyType,
        startTime,
        endTime,
        allottedTime
      } = this.form
      startTime = moment(startTime).format('YYYY-MM-DD')
      endTime = moment(endTime).format('YYYY-MM-DD')
      let path = (this.type === 'memberSet' && 'paymentExport') || 'renewExport'
      let res = await PaymentExport(
        {
          memberName: proposer,
          levelName,
          nowLevelName,
          membershipFees,
          amountPaid: payMoney,
          applyType,
          startTime,
          endTime,
          unit: allottedTime / 12 + '年'
        },
        path
      )
      if (res && res.code != 0) this.$message.error(res.msg)
    }
  },
  mounted() {}
}
</script>
<style scoped lang="less">
.title {
  margin-left: calc(25% - 80px);
  font-weight: bold;
  font-size: 18px;
  padding: 20px 0;
}
</style>
